package com.xiaomi.eco.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaomi.eco.service.FeiShuInterfaceService;
import com.xiaomi.eco.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class FeiShuInterfaceServiceImpl implements FeiShuInterfaceService {

    @Value("${Feishu.appId}")
    private String appId;

    @Value("${Feishu.appSecret}")
    private String appSecret;

    @Resource
    private RestTemplate restTemplate;

    private ObjectMapper objectMapper=new ObjectMapper();


    public String getinformation(){
        String requestTenantAccessToken="{\n" +
                "    \"app_id\": \""+appId+"\",\n" +
                "    \"app_secret\": \""+appSecret+"\"\n" +
                "}";
        String TenantAccessTokenUrl="https://open.f.mioffice.cn/open-apis/auth/v3/tenant_access_token/internal";
        String TenantAccessTokenRespon="";
        String tenantAccessToken="";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> TenantAccessTokenEntity = new HttpEntity<>(requestTenantAccessToken, headers);
        long start_time = System.currentTimeMillis();
        TenantAccessTokenRespon = restTemplate.postForObject(TenantAccessTokenUrl, TenantAccessTokenEntity, String.class);
        JsonNode TenantAccessTokenResponJsonNode = null;
        try {
            TenantAccessTokenResponJsonNode = objectMapper.readTree(TenantAccessTokenRespon);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        int expire = TenantAccessTokenResponJsonNode.get("expire").asInt();
        tenantAccessToken = TenantAccessTokenResponJsonNode.get("tenant_access_token").asText();
        long enn_time = System.currentTimeMillis();
        if((start_time-enn_time)/1000>expire){
            TenantAccessTokenRespon = restTemplate.postForObject(TenantAccessTokenUrl, TenantAccessTokenEntity, String.class);
            tenantAccessToken = TenantAccessTokenResponJsonNode.get("tenant_access_token").asText();
        }
        return tenantAccessToken;
    }

    public String getOpenId(){
        String tenantAccessToken=getinformation();
        String openId="";
        HttpHeaders headers = new HttpHeaders();
        //获取用户open_id
        String UserIdUrl = "https://open.f.mioffice.cn/open-apis/user/v1/batch_get_id?mobiles=15617512465";
        headers.clear();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + tenantAccessToken);
        HttpEntity<String> entity = new HttpEntity<>("body", headers);
        ResponseEntity<String> userIdResponse = restTemplate.exchange(UserIdUrl, HttpMethod.GET, entity, String.class);
        if (userIdResponse.getStatusCode().is2xxSuccessful()) {//响应成功
            String userIdBody = userIdResponse.getBody();
            JsonNode jsonNode = null;
            try {
                jsonNode = objectMapper.readTree(userIdBody);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }

            JsonNode dataNode = jsonNode.get("data");
            String msg = jsonNode.get("msg").asText();
            if(msg.equals("success")){
                JsonNode mobileUsersNode  = dataNode.get("mobile_users");
                Iterator<Map.Entry<String, JsonNode>> mobileUsersIterator  = mobileUsersNode.fields();
                while (mobileUsersIterator.hasNext()) {
                    Map.Entry<String, JsonNode> entry  = mobileUsersIterator.next();
                    String mobile  = entry.getKey();
                    JsonNode usersArrayNode  = entry.getValue();
                    // 解析 usersArrayNode 数组中的数据
                    for (JsonNode userNode  : usersArrayNode) {
                        openId = userNode.get("open_id").asText();
                    }
                }
            }
        } else {
            // 处理错误
            log.error("Error={}", userIdResponse.getStatusCode());
        }
        return openId;
    }

    public String postFeiShuRequest(String tenantAccessToken,String requestUrl,String requestTask){
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization","Bearer "+tenantAccessToken);

        //连接与超时设置
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1600000);
        requestFactory.setReadTimeout(1600000);
        restTemplate.setRequestFactory(requestFactory);

        //处理与请求
        String Taskresponse = null;
        try {
            HttpEntity<String> TaskEntity = new HttpEntity<>(requestTask, headers);
            Taskresponse = restTemplate.postForObject(requestUrl, TaskEntity, String.class);
//            log.info("postFeiShuRequest Response: " + Taskresponse);
        } catch (RestClientException e) {
            log.error("postFeiShuRequest error={}",e.getMessage());
        }
        return Taskresponse;
    }

    public ResponseEntity<String> exchangeFeiShuRequest(String tenantAccessToken,String requestUrl,String requestTask,HttpMethod requeststatus){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization","Bearer "+tenantAccessToken);

        //连接与超时设置
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setConnectTimeout(1600000);
        requestFactory.setReadTimeout(1600000);
        restTemplate.setRequestFactory(requestFactory);

        ResponseEntity<String> TaskResponse = null;
        try {
            HttpEntity<String> TaskEntity = new HttpEntity<>(requestTask, headers); // 使用空字符串作为请求体，或者完全省略（取决于你的RestTemplate版本）
            TaskResponse = restTemplate.exchange(requestUrl, requeststatus, TaskEntity, String.class);
//            log.info("exchangeFeiShuRequest response:"+TaskResponse);
        } catch (RestClientException e) {
            log.error("exchangeFeiShuRequest error={}",e.getMessage());
        }
        return TaskResponse;
    }
    
    
    public String selectTaskFeiShu(String taskId){
        String tenantAccessToken=getinformation();
        String searchUrl= "https://open.f.mioffice.cn/open-apis/task/v2/tasks/"+taskId+"?user_id_type=user_id";
        ResponseEntity<String> responseEntity=exchangeFeiShuRequest(tenantAccessToken,searchUrl,"",HttpMethod.GET);
        if(responseEntity==null){
            log.info("selectTaskFeiShu result is null");
            return null;
        }
        String resData=responseEntity.getBody();
        log.info("selectTaskFeiShu get resData:"+responseEntity.toString());
        return resData;
    }


    public boolean updateTaskFeishu(String requestUpdateTask,String taskId){
        String tenantAccessToken=getinformation();
        String PatchUrl="https://open.f.mioffice.cn/open-apis/task/v2/tasks/"+taskId;
        ResponseEntity<String> responseEntity=exchangeFeiShuRequest(tenantAccessToken,PatchUrl,requestUpdateTask,HttpMethod.PATCH);
        if(responseEntity==null){
            log.info("updateTaskFeishu fail");
            return false;
        }
        log.info("updateTaskFeishu get resData:"+responseEntity.toString());
        String resStatusCode= String.valueOf(responseEntity.getStatusCodeValue());
        return "200".equals(resStatusCode);
    }

    public boolean deleteTaskFeishu(String taskId){
        String tenantAccessToken=getinformation();
        String delUrl="https://open.f.mioffice.cn/open-apis/task/v2/tasks/"+taskId+"?user_id_type=user_id";
        ResponseEntity<String> responseEntity=exchangeFeiShuRequest(tenantAccessToken,delUrl,"",HttpMethod.DELETE);
        if(responseEntity==null){
            log.info("deleteTaskFeishu fail");
            return false;
        }
        log.info("deleteTaskFeishu get resData:"+responseEntity.toString());
        String resStatusCode= String.valueOf(responseEntity.getStatusCodeValue());
        return "200".equals(resStatusCode);
    }

    @Override
    public String insertTaskFeishu(String requestTask) {
        String tenantAccessToken=getinformation();
        String TaskUrl="https://open.f.mioffice.cn/open-apis/task/v2/tasks?user_id_type=user_id";
        String resData=postFeiShuRequest(tenantAccessToken,TaskUrl,requestTask);
        if(resData==null){
            log.info("insertTaskFeishu fail");
            return null;
        }
        log.info("insertInformation res={}",resData);
        return resData;
    }

    //完成任务or待完成任务需要配置
    //    public String completeTaskFeishu(String taskId,String tenantAccessToken){
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.set("Authorization","Bearer "+tenantAccessToken);
//        HttpEntity<String> completeTaskEntity = new HttpEntity<>(headers);
//        String completeTaskUrl="https://open.f.mioffice.cn/open-apis/task/v1/tasks/"+taskId+"/complete";
//        ResponseEntity<String> completeTaskResponse = restTemplate.postForEntity(completeTaskUrl, completeTaskEntity, String.class);
//        System.out.println(completeTaskResponse);
//        return completeTaskResponse.toString();
//    }
//
//    public String unCompleteTaskFeishu(String taskId,String tenantAccessToken){
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.set("Authorization","Bearer "+tenantAccessToken);
//        HttpEntity<String> uncompleteTaskEntity = new HttpEntity<>(headers);
//        String uncompleteTaskUrl="https://open.f.mioffice.cn/open-apis/task/v1/tasks/"+taskId+"/uncomplete";
//        ResponseEntity<String> uncompleteTaskResponse = restTemplate.postForEntity(uncompleteTaskUrl, uncompleteTaskEntity, String.class);
//        System.out.println("未完成任务:"+uncompleteTaskResponse);
//        return uncompleteTaskResponse.toString();
//    }
    
}
